import java.util.ArrayList;
import java.util.List;

/*
 * @lc app=leetcode.cn id=46 lang=java
 *
 * [46] 全排列
 *
 * https://leetcode-cn.com/problems/permutations/description/
 *
 * algorithms
 * Medium (74.51%)
 * Likes:    577
 * Dislikes: 0
 * Total Accepted:    95.2K
 * Total Submissions: 127.8K
 * Testcase Example:  '[1,2,3]'
 *
 * 给定一个 没有重复 数字的序列，返回其所有可能的全排列。
 * 
 * 示例:
 * 
 * 输入: [1,2,3]
 * 输出:
 * [
 * ⁠ [1,2,3],
 * ⁠ [1,3,2],
 * ⁠ [2,1,3],
 * ⁠ [2,3,1],
 * ⁠ [3,1,2],
 * ⁠ [3,2,1]
 * ]
 * 
 */

// @lc code=start
class Solution {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(nums,new boolean[nums.length], new ArrayList<Integer>(), res);
        return res;
    }

    void dfs(int[] nums,boolean[] flag, List<Integer> temp, List<List<Integer>> res) {

        if (temp.size() == nums.length) {
            res.add(new ArrayList<>(temp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!flag[i]) {
                temp.add(nums[i]);
                flag[i] = true;
                dfs(nums, flag, temp, res);
                flag[i] = false;
                temp.remove(temp.size()-1);
            }
        }
    }
}
// @lc code=end

